package com.rpframework.module.common.bottom.interceptor;


import com.rpframework.core.json.JsonException;
import com.rpframework.core.json.JsonResp;
import com.rpframework.module.common.bottom.entity.enums.SourceType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


/**
 * 接口权限拦截器
 *
 * @author 刘兴
 */
public class JurisdictionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        JsonResp validate;
        try {
            validate = SourceType.validate(request);
        } catch (JsonException e) {
            PrintWriter writer = response.getWriter();
            writer.print(e.getJsonResp().toJson());
            writer.close();
            return false;
        }
        if (validate != null) {
            PrintWriter writer = response.getWriter();
            writer.print(validate.toJson());
            writer.close();
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

}